<template>
  <div>
    <header-component ></header-component>

    <!--我要下注-->
    <div class="rab_xiazhu ">
      <div class="rab_xiazhu_biaoti">{{$t('carGame.want_bet')}}
        <ul>
          <li @click="changeGame(3)" v-bind:class="curGame == 3?'on':''" class="" >{{$t('carGame.track3')}}</li>
          <li @click="changeGame(5)" v-bind:class="curGame == 5?'on':''">{{$t('carGame.track5')}}</li>
          <li @click="changeGame(7)" v-bind:class="curGame == 7?'on':''">{{$t('carGame.track7')}}</li>
        </ul>
      </div>

      <div class="rab_daojishi rab_bg">
        <p class="rab_daojishi_p1" style="font-size: 15px">
          <span class="cur_times">
            {{$t('carGame.rounds')}}<span v-if="gameListData">{{gameListData | getGameId(curGame)}}</span>
          </span>
          <span class="cur_betinfo">
            {{$t('carGame.bet_num')}} <span>{{curBetNum}}</span>
          </span>
          <i v-show="stopBetTag !== 2" class="iconfont icon-shijian1" id="shijian1"></i>
          <span v-show="!stopBetTag">{{cutDown}} s</span>
          <span v-show="stopBetTag == 1 && cdData.lottoCD !== 0" style="display: none">{{$t('carGame.lottery_now')}} {{cdData.lottoCD}}</span>
          <span v-show="showLotteryLate" style="display: none;white-space: nowrap;">{{$t('carGame.lottery_late_hint')}}</span>
          <span v-show="stopBetTag == 2 && winCar['track' + curGame] !== 0" style="display: none;color: #fff;margin-left: 20px;">{{$t('carGame.win_track')}}
            <span style="color: #e7b425"> {{winCar['track' + curGame]}}</span> ，<span style="color: #02bf01;">{{cdData.nextCD}} </span>{{$t('carGame.go_next_hint')}}
          </span>
        </p>
        <p @click="nextGame" class="rab_daojishi_next">{{$t('carGame.next_round')}}</p>
        <p>{{$t('carGame.minute_game')}}</p>
        <p>{{$t('carGame.game_des')}}</p>
      </div>
      <!--下注赛道-->

      <div class="rab_saidao rab_bg" v-show="curGame == 3" style="display: none;">
        <ul>
          <li @click="chooseTrack(3,1)" v-bind:class="{on: track3[0].on}">
            <div class="saiche" v-bind:class="{carInit: isCarInit}" v-bind:style="track3[0].runTag ? track3[0].runTag: ''">
              <img src="../assets/image/saiche1.png" alt="">
            </div>
            <p class="saidaoshuzi">1</p>
            <span v-show="stopBetTag === 0" class="xiazhubtn" @click.stop="chooseCar(3,1)">{{$t('carGame.bet_track')}}</span>
          </li>
          <li @click="chooseTrack(3,2)" v-bind:class="{on: track3[1].on}">
            <div class="saiche" v-bind:class="{carInit: isCarInit}" v-bind:style="track3[1].runTag ? track3[1].runTag: ''">
              <img src="../assets/image/saiche2.png" alt="">
            </div>
            <p class="saidaoshuzi">2</p>
            <span v-show="stopBetTag === 0" class="xiazhubtn" @click.stop="chooseCar(3,2)">{{$t('carGame.bet_track')}}</span>
          </li>
          <li @click="chooseTrack(3,3)" v-bind:class="{on: track3[2].on}">
            <div class="saiche" v-bind:class="{carInit: isCarInit}" v-bind:style="track3[2].runTag ? track3[2].runTag: ''">
              <img src="../assets/image/saiche3.png" alt="">
            </div>
            <p class="saidaoshuzi">3</p>
            <span v-show="stopBetTag === 0" class="xiazhubtn" @click.stop="chooseCar(3,3)">{{$t('carGame.bet_track')}}</span>
          </li>
        </ul>
      </div>

      <div class="rab_saidao rab_bg" v-show="curGame == 5" style="display: none;">
        <ul>
          <li @click="chooseTrack(5,1)" v-bind:class="track5[0].on?'on':''">
            <div class="saiche" v-bind:class="{carInit: isCarInit}" v-bind:style="track5[0].runTag ? track5[0].runTag: ''">
              <img src="../assets/image/saiche3.png" alt=""></div>
            <p class="saidaoshuzi">1</p>
            <span v-show="stopBetTag === 0" class="xiazhubtn" @click.stop="chooseCar(5,1)">{{$t('carGame.bet_track')}}</span>
          </li>
          <li @click="chooseTrack(5,2)" v-bind:class="track5[1].on?'on':''">
            <div class="saiche" v-bind:class="{carInit: isCarInit}" v-bind:style="track5[1].runTag ? track5[1].runTag: ''">
              <img src="../assets/image/saiche5.png" alt=""></div>
            <p class="saidaoshuzi">2</p>
            <span v-show="stopBetTag === 0" class="xiazhubtn" @click.stop="chooseCar(5,2)">{{$t('carGame.bet_track')}}</span>
          </li>
          <li @click="chooseTrack(5,3)" v-bind:class="track5[2].on?'on':''">
            <div class="saiche" v-bind:class="{carInit: isCarInit}" v-bind:style="track5[2].runTag ? track5[2].runTag: ''">
              <img src="../assets/image/saiche1.png" alt=""></div>
            <p class="saidaoshuzi">3</p>
            <span v-show="stopBetTag === 0" class="xiazhubtn" @click.stop="chooseCar(5,3)">{{$t('carGame.bet_track')}}</span>
          </li>
          <li @click="chooseTrack(5,4)" v-bind:class="track5[3].on?'on':''">
            <div class="saiche" v-bind:class="{carInit: isCarInit}" v-bind:style="track5[3].runTag ? track5[3].runTag: ''">
              <img src="../assets/image/saiche4.png" alt=""></div>
            <p class="saidaoshuzi">4</p>
            <span v-show="stopBetTag === 0" class="xiazhubtn" @click.stop="chooseCar(5,4)">{{$t('carGame.bet_track')}}</span>
          </li>
          <li @click="chooseTrack(5,5)" v-bind:class="track5[4].on?'on':''">
            <div class="saiche" v-bind:class="{carInit: isCarInit}" v-bind:style="track5[4].runTag ? track5[4].runTag: ''">
              <img src="../assets/image/saiche2.png" alt=""></div>
            <p class="saidaoshuzi">5</p>
            <span v-show="stopBetTag === 0" class="xiazhubtn" @click.stop="chooseCar(5,5)">{{$t('carGame.bet_track')}}</span>
          </li>
        </ul>
      </div>
      <div class="rab_saidao rab_bg"  v-show="curGame == 7" style="display: none;">
        <ul>
          <li @click="chooseTrack(7,1)" v-bind:class="track7[0].on?'on':''">
            <div class="saiche" v-bind:class="{carInit: isCarInit}" v-bind:style="track7[0].runTag ? track7[0].runTag: ''">
              <img src="../assets/image/saiche7.png" alt="">
            </div>
            <p class="saidaoshuzi">1</p>
            <span v-show="stopBetTag === 0" class="xiazhubtn" @click.stop="chooseCar(7,1)">{{$t('carGame.bet_track')}}</span>
          </li>
          <li @click="chooseTrack(7,2)" v-bind:class="track7[1].on?'on':''">
            <div class="saiche" v-bind:class="{carInit: isCarInit}" v-bind:style="track7[1].runTag ? track7[1].runTag: ''">
              <img src="../assets/image/saiche6.png" alt=""></div>
            <p class="saidaoshuzi">2</p>
            <span v-show="stopBetTag === 0" class="xiazhubtn" @click.stop="chooseCar(7,2)">{{$t('carGame.bet_track')}}</span>
          </li>
          <li @click="chooseTrack(7,3)" v-bind:class="track7[2].on?'on':''">
            <div class="saiche" v-bind:class="{carInit: isCarInit}" v-bind:style="track7[2].runTag ? track7[2].runTag: ''">
              <img src="../assets/image/saiche5.png" alt=""></div>
            <p class="saidaoshuzi">3</p>
            <span v-show="stopBetTag === 0" class="xiazhubtn" @click.stop="chooseCar(7,3)">{{$t('carGame.bet_track')}}</span>
          </li>
          <li @click="chooseTrack(7,4)" v-bind:class="track7[3].on?'on':''">
            <div class="saiche" v-bind:class="{carInit: isCarInit}" v-bind:style="track7[3].runTag ? track7[3].runTag: ''">
              <img src="../assets/image/saiche4.png" alt=""></div>
            <p class="saidaoshuzi">4</p>
            <span v-show="stopBetTag === 0" class="xiazhubtn" @click.stop="chooseCar(7,4)">{{$t('carGame.bet_track')}}</span>
          </li>
          <li @click="chooseTrack(7,5)" v-bind:class="track7[4].on?'on':''">
            <div class="saiche" v-bind:class="{carInit: isCarInit}" v-bind:style="track7[4].runTag ? track7[4].runTag: ''">
              <img src="../assets/image/saiche3.png" alt=""></div>
            <p class="saidaoshuzi">5</p>
            <span v-show="stopBetTag === 0" class="xiazhubtn" @click.stop="chooseCar(7,5)">{{$t('carGame.bet_track')}}</span>
          </li>
          <li @click="chooseTrack(7,6)" v-bind:class="track7[5].on?'on':''">
            <div class="saiche" v-bind:class="{carInit: isCarInit}" v-bind:style="track7[5].runTag ? track7[5].runTag: ''">
              <img src="../assets/image/saiche2.png" alt=""></div>
            <p class="saidaoshuzi">6</p>
            <span v-show="stopBetTag === 0" class="xiazhubtn" @click.stop="chooseCar(7,6)">{{$t('carGame.bet_track')}}</span>
          </li>
          <li @click="chooseTrack(7,7)" v-bind:class="track7[6].on?'on':''">
            <div class="saiche" v-bind:class="{carInit: isCarInit}" v-bind:style="track7[6].runTag ? track7[6].runTag: ''">
              <img src="../assets/image/saiche1.png" alt=""></div>
            <p class="saidaoshuzi">7</p>
            <span v-show="stopBetTag === 0" class="xiazhubtn" @click.stop="chooseCar(7,7)">{{$t('carGame.bet_track')}}</span>
          </li>
        </ul>
      </div>
      <div class="rab_daojishi pb15  rab_bg bor-r-5 ">
        <!-- <p class="rab_daojishi_next">进入下一轮</p> -->
        <div class="rab_chiyou">
          <ul>
            <li><i class="iconfont icon-shouyi1"></i>{{balance.eos}}</li>
            <li><i class="iconfont icon-rab"></i>{{balance.rab}}</li>
          </ul>
        </div>
        <div class="rab_shouyi">
          <ul>
            <i class="iconfont icon-rab"></i>
            <li>{{$t('carGame.bet_can')}}：10 &nbsp;RAB</li>
            <li>{{$t('carGame.bet_available')}}：10 &nbsp;RAB</li>
            <i class="iconfont icon-wenhao" @click="showRabDes"></i>
          </ul>
        </div>
      </div>

      <!--弹窗-->
      <div v-show="showBetHint" class="tanchuangbg" style="display: none">
        <!--下注弹窗-->
        <div class="xiazhutc">
          <p class="xiazhutc_p1">{{$t('carGame.bet_sure')}}<i @click="hideBetHint" class="iconfont icon-guanbi" ></i></p>
          <P class="xiazhutc_p2">{{$t('carGame.cost')}}&nbsp;<span class="cr_lvse">{{betNum['carType' + curGame]}}</span>&nbsp;EOS</P>
          <P class="xiazhutc_p2">{{$t('carGame.bet_track')}}</P>
          <div class="xiazhutc_btn mrb30p" @click="confirmBet" ><span>{{$t('carGame.bet_sure')}}</span></div>
        </div>
      </div>
    </div>
    <rank-list></rank-list>
    <!--开奖记录-->
    <div class="rab_bg rbg_kaijiang">
      <div class="rab_title" style="background-color: #1e3c72;line-height: 0;">
        <div @click="toggleShowList(0)" v-bind:class="{on: !showBetRecord}" class="title-tab" >
          {{$t('carGame.lottery_record')}}
        </div>
        <div @click="toggleShowList(1);getBetRecord()"  v-bind:class="{on: showBetRecord}" class="title-tab ">
          {{$t('carGame.bet_record')}}
        </div>
      </div>

      <ul v-show="!showBetRecord" class="kj-record">
        <li>
          <span>{{$t('carGame.rows_rounds')}}</span>
          <span>{{$t('carGame.time')}}</span>
          <span>{{$t('carGame.win_num')}}</span>
          <span>{{$t('carGame.win_list')}}</span>
        </li>
        <!--<li>-->
        <!--<span>1</span>-->
        <!--<span>18:23</span>-->
        <!--<span>5</span>-->
        <!--<span @click="showWiners(222)"><a href="javascript:;">查看名单</a></span>-->
        <!--</li>-->
        <li v-for="item in trackRecord" v-bind:key="item.gameid">
          <span>{{item.gameid | formatGaimeId}}</span>
          <span>{{item.createtime | timestampToDate('MM-dd hh:mm', lang)}}</span>
          <span>{{item.number > 0 ? item.number : $t('carGame.lottery_now')}}</span>
          <span >
            <a v-show="item.gameid !== curRounds" @click="showWiners(item.gameid)" href="javascript:;">{{$t('carGame.query_list')}}</a>
          </span>
        </li>
      </ul>
      <!--bet record-->
      <ul v-show="showBetRecord" class="bet-record">
        <li>
          <span>{{$t('carGame.time')}}</span>
          <span>{{$t('carGame.track_amount')}}</span>
          <span>{{$t('carGame.round')}}</span>
          <span>{{$t('carGame.game_type')}}</span>
          <span>{{$t('carGame.track')}}</span>
        </li>
        <li v-for="item in betsRecord" v-bind:key="item.id">
          <span>{{item.bettime | timestampToDate('MM-dd hh:mm', lang)}}</span>
          <span>{{item.reward}}</span>
          <span>{{item.gameid | formatGaimeId}}</span>
          <span>{{item.game}}</span>
          <span>{{item.digital}}</span>
        </li>
      </ul>
    </div>
    <rabinfo-component ref="rabInfo"></rabinfo-component>
    <winers-component :game-id="winerGameId" ref="winers"></winers-component>
    <footer-component></footer-component>
  </div>

</template>

<script>
import { mapActions } from 'vuex'
import headerComponent from '@/view/common/header'
import footerComponent from '@/view/common/footer'
import RabinfoComponent from '../components/rabInfo.vue'
import WinersComponent from '../components/winers.vue'
import RankList from '../components/rankList.vue'

export default {
  name: 'index',
  data () {
    return {
      curGame: 3, // 3 5 7
      gameListData: [],
      betListData: [],
      gameBaseData: null,
      eos: null, // eos实例
      eoswrite: null,
      betNum: {
        carType3: '1.0000',
        carType5: '3.0000',
        carType7: '5.0000'
      },
      track3: [{on: false, isBet: false, winTag: false, runTag: false}, {on: false, isBet: false, winTag: false, runTag: false}, {on: true, isBet: false, winTag: false, runTag: false}],
      track5: [{on: false, isBet: false, winTag: false, runTag: false}, {on: false, isBet: false, winTag: false, runTag: false}, {on: false, isBet: false, winTag: false, runTag: false},
        {on: false, isBet: false, winTag: false, runTag: false}, {on: false, isBet: false, winTag: false, runTag: false}],
      track7: [{on: false, isBet: false, winTag: false, runTag: false}, {on: false, isBet: false, winTag: false, runTag: false}, {on: false, isBet: false, winTag: false, runTag: false},
        {on: false, isBet: false, winTag: false, runTag: false}, {on: false, isBet: false, winTag: false, runTag: false},
        {on: false, isBet: false, winTag: false, runTag: false}, {on: false, isBet: false, winTag: false, runTag: false}],
      showBetHint: false, // 下注提示
      isCarInit: false, // 是track否初始化中
      isInitGame: false, // 是否初始化游戏
      stopBetTag: 0, // 显示停止下注标志 0: 正常下注 1：开奖中 2:已开奖
      screenWidth: 0, // 容器宽度
      differTime: 0, // 本地时间与服务器时间的差
      serviceTime: 0, // 服务器时间
      cutDown: 0, // 倒计时
      getTimes: 10,
      coolDownTag: false,
      gameRecord: [], // 开奖记录
      timeFormat: 'yyyy-MM-dd',
      winerGameId: '', // 查看中奖id
      betCD: null, // 下注计时器
      startlottoCD: null, // 开奖计时器
      nextGameCD: null, // 下一轮计时器
      betNumCD: null, // 下注数计时器
      cdData: { // 倒计时时间
        lottoCD: '', // 开奖倒计时
        nextCD: 5 // 进入下一轮倒计时
      },
      winCar: { // 获奖号码
        track3: 0,
        track5: 0,
        track7: 0
      },
      betNumInterval: null,
      carGame_creation: 0,
      perCarGameTime: 60,
      car_cardinal: 100000000,
      car_maxgameid: 0,
      curBetNum: 0, // 当前下注数
      showBetRecord: false, // 显示下注记录/开奖记录
      lotteryRes: [] // 开奖数据
    }
  },
  components: {
    headerComponent,
    footerComponent,
    'rabinfo-component': RabinfoComponent,
    'winers-component': WinersComponent,
    'rank-list': RankList
  },
  computed: {
    user () {
      return this.$store.getters.getAccount
    },
    balance () {
      return this.$store.getters.getBalance
    },
    trackRecord () {
      if (!this.gameRecord.length) {
        return []
      }
      var tempGameType = this.curGame
      var tempRecord = this.gameRecord.filter(item => {
        return item.game === tempGameType
      })
      if (tempRecord[0] === undefined) {
        return {}
      }
      if (this.gameListData.length > 0 && this.gameListData.find(item => item.gameid === tempRecord[0].gameid)) {
        return tempRecord.slice(1, 21)
      }
      return tempRecord.slice(0, 20)
    },
    betsRecord () {
      return this.betListData
    },
    lang () {
      return this.$store.getters.getLang
    },
    curRounds () {
      var curGameData = this.gameListData.find(item => {
        return item.game === this.curGame
      })
      return curGameData.gameid || ''
    },
    showLotteryLate () {
      return (this.stopBetTag === 2 && this.winCar['track' + this.curGame] === 0) || (this.stopBetTag === 1 && this.cdData.lottoCD === 0)
    }
  },
  watch: {
    user (userData) {
      this.getMyBalance(userData.name)
    }
  },
  created () {
    this.getServiceTime()
    this.getGameCreation()
    this.getGameRecordInterval()
    this.screenWidth = window.screen.width > 1200 ? 1200 : window.screen.width
    // document.addEventListener('visibilitychange', () => {
    //   console.warn('visibilitychange: ', document.visibilityState)
    // })
  },
  methods: {
    ...mapActions([
      'setBalance',
      'setDifTime'
    ]),
    gameMongodb (url, json, callback) {
      const axios = require('axios')
      axios.post(this.$config.gameMongodbApiUrl + '/cargame/' + url, json).then(function (response) {
        callback(response.data)
      }).catch(function (error) {
        console.log(error)
      })
    },
    changeGame (val) {
      if (this.curGame !== val) {
        this.curGame = val
        this.curBetNum = 0
        this.getBetNum()
      }
    },
    showRabDes () {
      // this.$refs.winers.toggleShow()
      this.$refs.rabInfo.toggleShow()
    },
    hideBetHint () {
      this.showBetHint = false
    },
    showWiners (id) {
      this.winerGameId = id
      // this.$router.push({name: 'winerList', params: {id: id}})
      this.$refs.winers.toggleShow()
    },
    async getGameCreation () {
      if (!this.eos) {
        await this.$scatterJs.scatter.connect(this.$config.gameName)
        this.eos = this.$scatterJs.scatter.eos(this.$config.network, this.$eosjs)
        this.eoswrite = this.$scatterJs.scatter.eos(this.$config.write_network, this.$eosjs)
      }
      this.eos.getTableRows({
        code: this.$config.cont_owner,
        scope: this.$config.cont_owner,
        table: 'carinfo',
        limit: 1,
        json: true
      }).then(res => {
        this.carGame_creation = res.rows[0].creation
        this.car_maxgameid = res.rows[0].maxgameid
      }).catch(e => {
        console.log('carinfo table e:', e)
      })
    },
    // 获取余额信息
    getMyBalance (name) {
      if (!name) {
        return
      }
      var tempBalance = {
        rab: '0.0000 RAB',
        eos: '0.0000 EOS'
      }
      // 获取我的RAB余额
      this.eos.getCurrencyBalance({code: this.$config.token_issuer, account: name, symbol: 'RAB'}).then(res => {
        console.log('RAB info: ', res)
        if (res.length === 0) {
          tempBalance.rab = '0.0000 RAB'
        } else {
          tempBalance.rab = res[0]
        }
      }).catch(e => {
        console.log('get RAB err: ', e)
      })
      this.eos.getCurrencyBalance({code: 'eosio.token', account: name, symbol: 'EOS'}).then(res => {
        console.log('EOS info: ', res)
        if (res.length === 0) {
          tempBalance.eos = '0.0000 EOS'
        } else {
          tempBalance.eos = res[0]
        }
      }).catch(e => {
        console.log('get RAB err: ', e)
      })
      this.setBalance(tempBalance)
    },
    getServiceTime () {
      var newwork = this.$config.network
      var url = newwork.protocol + '://' + newwork.host + ':' + newwork.port + '/v1/chain/get_info'
      this.$http.get(url, [{timeout: 3000}]).then(res => {
        var tmp = res.body.head_block_time.split('.')
        var serviceTime = 0
        if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
          serviceTime = ((new Date(tmp[0]).getTime() / 1000)) * 1000
        } else {
          console.log('noli')
          serviceTime = ((new Date(tmp[0]).getTime() / 1000) + (8 * 60 * 60)) * 1000
        }
        var difTime = new Date().getTime() - serviceTime
        this.differTime = difTime
        this.setDifTime(difTime)
        this.serviceTime = serviceTime
        if (!this.isInitGame) {
          this.initGame()
        }
        console.log('time diff: ', parseInt(difTime / 1000))
        setTimeout(() => {
          this.getServiceTime() // 时间校准
        }, 300000)
      }).catch(e => {
        console.log('service time err: ', e)
        setTimeout(() => {
          this.getServiceTime()
        }, 5000)
      })
    },
    getGameInfo (game) {
      var now = (new Date().getTime() - this.differTime) / 1000
      var num = Math.ceil((now - this.carGame_creation) / this.perCarGameTime)
      var gameid = (game * this.car_cardinal) + num
      var createtime = this.carGame_creation + (this.perCarGameTime * (num - 1))
      var info = {
        game: game,
        gameid: gameid,
        createtime: createtime
      }
      return info
    },
    // 当前进行的赛车
    getCarRunning () {
      var running = [
        this.getGameInfo(3),
        this.getGameInfo(5),
        this.getGameInfo(7)
      ]
      var map = running.map(function (item) {
        return item
      })
      this.gameListData = map
      return map
    },
    // 获取中奖结果
    getWinRes (gameId) {
      var curGameData = this.gameListData.find(item => {
        return item.gameid === gameId
      })
      if (!curGameData) return
      this.eos.getTableRows({
        code: this.$config.cont_owner,
        scope: this.$config.cont_owner,
        table: 'cargame',
        limit: 1,
        index_position: '3',
        lower_bound: gameId + '',
        key_type: 'i64',
        upper_bound: gameId + '',
        json: true
      }).then(res => {
        // this.preSellData = res.rows[0]
        if (this.gameListData.find(item => item.gameid === res.rows[0].gameid)) { // 当前场次才重新获取或刷新赛车
          console.log('win:' + res.rows[0].number)
          this.getTimes = 10
          this.carRunResult(res.rows, gameId)
        }
      }).catch(e => {
        console.log('cargame table e:', e.message)
        if (e.message === 'Cannot read property \'id\' of undefined') {
          // this.carRunResult(null)
        }
      })
    },
    getBetRecord () {
      this.gameMongodb('getBetList', {user: this.user.name, limit: 30}, data => {
        for (var i = 0; i < data.data.length; i++) {
          var game = Math.floor(data.data[i].gameid / this.car_cardinal)
          this.betListData[i] = data.data[i]
          this.betListData[i].game = game
          this.betListData[i].id = i + 1
          var gameinfo = this.getGameInfo(game)
          if (gameinfo.gameid === data.data[i].gameid) {
            this.betListData[i].reward = '-'
          }
        }
      })
    },
    getGameRecord () {
      console.log('get record !!!')
      this.gameMongodb('getGameList', {limit: 100}, data => {
        this.gameRecord = data.data
      })
    },
    getGameRecordInterval () {
      setInterval(() => {
        this.getGameRecord()
      }, 10000)
    },
    // //////////// 初始化///////////////
    // 初始化游戏数据
    async initGame () {
      if (this.carGame_creation === 0 || isNaN(this.serviceTime)) {
        setTimeout(() => {
          this.initGame()
        }, 200)
      } else {
        this.initTrack()
        this.clearNextGameCD()
        this.clearLottoCD()
        this.clearBetCD()
        this.isInitGame = true
        this.stopBetTag = 0
        let gameData = await this.getCarRunning()
        console.log('game data: ', gameData)
        this.curBetNum = 0
        this.getBetNumInterval()
        this.initCutDown()
        this.getGameRecord()
      }
    },
    // 倒计时
    initCutDown () {
      var curBetData = this.getBetGameId()
      var curGameData = this.gameListData.find(item => {
        return item.game === this.curGame
      })
      console.log('curGameData', curGameData)
      if (!curGameData) {
        // this.$message({message: this.$t('carGame.game_not_begin')})
        return
      }
      var createTime = curGameData.createtime * 1000
      var curServiceTime = new Date().getTime() - this.differTime
      if (curServiceTime - createTime >= 50000) {
        this.cutDown = 0
        this.stopBetTag = 1
        this.startLotto()
        this.getWinRes(curBetData || curGameData.gameid)
      } else if (curServiceTime - createTime >= 0) {
        this.cutDown = Math.ceil(50 - ((curServiceTime - createTime) / 1000))
        this.betCD = setInterval(() => {
          if (this.cutDown === 0) {
            clearInterval(this.betCD)
            this.stopBetTag = 1
            this.startLotto()
            setTimeout(() => {
              this.getWinRes(this.getBetGameId() || curGameData.gameid)
            }, 6000)
            setTimeout(() => {
              this.getGameRecord()
            }, 10500)
          } else {
            this.cutDown = this.cutDown - 1
          }
        }, 1000)
      } else {
        setTimeout(() => {
          this.initGame()
        }, createTime - curServiceTime)
      }
    },
    clearBetCD () {
      if (this.betCD) {
        clearInterval(this.betCD)
        this.betCD = null
        this.cutDown = 0
      }
    },
    // 赛道初始化
    initTrack () {
      this.isCarInit = true
      for (let i of [3, 5, 7]) {
        let newCarList = [...this['track' + i]]
        newCarList.map(function (item) {
          item.runTag = false
          item.winTag = false
          item.isBet = false
        })
        this['track' + i] = newCarList
      }
      setTimeout(() => {
        this.isCarInit = false
      }, 100)
    },
    // //////////交互///////
    // 下一轮
    nextGame () {
      console.log('next game !')
      if (!this.differTime) {
        console.log('time services is uncompleted !')
        return
      }
      var curServiceTime = new Date().getTime() - this.differTime
      if (!this.gameListData || this.gameListData.length === 0) {
        this.initGame()
        return
      }
      var createTime = this.gameListData[0].createtime * 1000
      if (curServiceTime - createTime <= 0) {
        this.$message({message: this.$t('carGame.game_unactive_hint'), type: 'warning'})
        return
      } else if (curServiceTime - createTime <= 60000) {
        this.$message({message: this.$t('carGame.game_active_hint'), type: 'warning'})
        return
      }
      if (this.coolDownTag) return
      this.coolDownTag = true
      setTimeout(() => {
        this.coolDownTag = false
      }, 2000)
      this.initGame()
    },
    // bet
    async confirmBet () {
      console.log('confirm choose car !')
      this.hideBetHint()
      if (this.canBet()) {
        console.log('can bet !')
        var betNum = this.$config.betNum['track' + this.curGame]
        var curIndex = this['track' + this.curGame].findIndex(item => item.on === true)
        var betParam = 'bet-1-' + (curIndex + 1)
        var inviter = localStorage.getItem('rab_ivt') || ''
        if (inviter) {
          betParam = betParam + '-' + inviter
        }
        try {
          // betParam = '1-121-222'
          let result = await this.eoswrite.transfer(this.user.name, this.$config.cont_owner, betNum, betParam, true)
          console.log('bet NUM: ', betNum)
          console.log('bet succ: ', result)
          this.$message({message: this.$t('carGame.bet_suc'), type: 'success'})
          this['track' + this.curGame][curIndex].isBet = true
          this.car_maxgameid++
          setTimeout(() => {
            this.getBetNum()
            this.getGameRecord()
            this.getBetRecord()
            this.getMyBalance(this.user.name)
          }, 50)
        } catch (e) {
          console.log('bet error: ', e)
          var eCode = this.$utils.getErrorCode(e)
          var errText
          if (eCode) {
            errText = this.$t('errCode.' + e.message)
          } else {
            errText = this.$t('carGame.bet_fail')
          }
          this.$message({message: errText, type: 'error'})
        }
      }
    },
    // 选择赛道
    chooseTrack (type, idx) {
      var trackData = this['track' + type]
      var item = trackData[idx - 1]
      if (item.on) {
        item.on = false
        trackData.splice(idx - 1, 1, this.$utils.simpleCopy(item))
      } else {
        for (let i = 0; i < trackData.length; i++) {
          let item = trackData[i]
          if (item.on) {
            item.on = false
            trackData.splice(i, 1, this.$utils.simpleCopy(item))
            break
          }
        }
        item.on = true
        trackData.splice(idx - 1, 1, this.$utils.simpleCopy(item))
      }
    },
    // 选择车
    chooseCar (type, idx) {
      console.log('choose cart')
      var trackData = this['track' + type]
      var item = trackData[idx - 1]
      if (!item.on) {
        this.chooseTrack(type, idx)
      }
      if (!this.canBet()) {
        console.log('游戏已结束！')
        return
      }
      this.showBetHint = true
    },
    // 赛车结果
    async carRunResult (data, gameId) {
      this.lotteryRes = []
      if (data === null) {
        this.nextGameIntval()
        return
      }
      // if (this.startlottoCD) {
      //   this.clearLottoCD()
      // }
      if (!data || data.length === 0) {
        console.log('result data err !')
        return
      }
      var tempArry = [3, 5, 7]
      var tempArryRes = tempArry.filter(item => item !== parseInt(gameId / 100000000))
      var track2Id = (gameId % 100000000) + (100000000 * tempArryRes[0])
      var track3Id = (gameId % 100000000) + (100000000 * tempArryRes[1])
      console.log(track2Id)
      console.log(track3Id)
      var track2Res = await this.eos.getTableRows({
        code: this.$config.cont_owner,
        scope: this.$config.cont_owner,
        table: 'cargame',
        limit: 1,
        index_position: '3',
        lower_bound: track2Id + '',
        key_type: 'i64',
        upper_bound: track2Id + '',
        json: true
      })
      var track3Res = await this.eos.getTableRows({
        code: this.$config.cont_owner,
        scope: this.$config.cont_owner,
        table: 'cargame',
        limit: 1,
        index_position: '3',
        lower_bound: track3Id + '',
        key_type: 'i64',
        upper_bound: track3Id + '',
        json: true
      })
      var tempData = [...data]
      if (track2Res.rows && track2Res.rows.length > 0) {
        if (track2Res.rows[0].gameid === track2Id) {
          tempData.push(track2Res.rows[0])
        }
      }
      if (track3Res.rows && track3Res.rows.length > 0) {
        if (track3Res.rows[0].gameid === track3Id) {
          tempData.push(track3Res.rows[0])
        }
      }
      this.lotteryRes = tempData
    },
    runLottery () {
      var tempData = this.lotteryRes
      var curGameIds = this.gameListData.map(item => {
        return item.gameid
      })
      if (!this.gameListData.find(item => item.gameid === tempData[0].gameid)) return
      this.winCar = {
        track3: 0,
        track5: 0,
        track7: 0
      }
      if (tempData.length > 0) {
        tempData.map(gameCell => {
          if (curGameIds.indexOf(gameCell.gameid) !== -1) {
            var type = gameCell.game
            let newCarList = [...this['track' + type]]
            newCarList.map(function (item, idx) {
              // item.runTag = true
              if (idx === gameCell.number - 1) {
                item.winTag = true
                item.runTag = this.getRunDistance(true)
              } else {
                item.runTag = this.getRunDistance(false)
              }
            }, this)
            this['track' + type] = newCarList
            this.winCar['track' + type] = gameCell.number
          }
        })
        this.stopBetTag = 2
        this.nextGameIntval()
        this.lotteryRes = []
      }
    },
    // 获取车跑的距离
    getRunDistance (winTag) {
      var localRightDistance = this.screenWidth === 1200 ? 90 : 20
      if (winTag) {
        return 'right: ' + localRightDistance + 'px'
      } else {
        var trackWidth = this.screenWidth - 20 - 100 - 70 // 赛道长度
        var distanceRight = ((Math.random() * 4 + 1) / 10) * trackWidth + 100
        return 'right: ' + distanceRight + 'px'
      }
    },
    // 是否可下注
    canBet () {
      if (!this.user) { // 未登录
        this.$message({message: this.$t('carGame.login_first'), type: 'error'})
        return false
      }
      var curGameData = this.gameListData.find(item => {
        return item.game === this.curGame
      })
      console.log('curGameData', curGameData)
      var createTime = curGameData.createtime * 1000
      var curServiceTime = new Date().getTime() - this.differTime
      if (curServiceTime - createTime >= 50000) {
        this.$message({message: this.$t('carGame.game_over'), type: 'warning'})
        return false
      }
      var curIndex = this['track' + this.curGame].findIndex(item => item.on === true)
      if (this['track' + this.curGame][curIndex].isBet) {
        this.$message({message: this.$t('carGame.bet_car_repeat'), type: 'warning'})
        return false
      }
      return true
    },
    // 找最小id
    findMinGameId (data, type) {
      var key = type || 'gameid'
      if (!data || data.length === 0) {
        return false
      } else {
        var minId
        data.map(item => {
          if (!minId) {
            minId = item[key]
          } else {
            if (minId > item[key]) {
              minId = item[key]
            }
          }
        })
        return minId
      }
    },
    // 开奖倒计时
    startLotto () {
      if (this.startlottoCD) {
        this.clearLottoCD()
      }
      this.cdData.lottoCD = 10
      this.startlottoCD = setInterval(() => {
        if (this.cdData.lottoCD === 1 && this.lotteryRes.length > 0) {
          this.runLottery()
          clearInterval(this.startlottoCD)
          return
        }
        if (this.cdData.lottoCD === 0) {
          // this.$message({message: this.$t('carGame.lottery_late_hint')})
          setTimeout(() => {
            this.nextGame()
          }, 2000)
          clearInterval(this.startlottoCD)
          this.startlottoCD = null
          return
        }
        this.cdData.lottoCD -= 1
      }, 1000)
    },
    // 清除开奖倒计时
    clearLottoCD () {
      this.cdData.lottoCD = ''
      if (this.startlottoCD) {
        clearInterval(this.startlottoCD)
        this.startlottoCD = null
      }
    },
    nextGameIntval () { // 下轮游戏倒计时winCar
      if (this.nextGameCD) {
        this.clearNextGameCD()
      }
      this.cdData.nextCD = 5
      this.nextGameCD = setInterval(() => {
        if (this.cdData.nextCD === 0) {
          this.initGame()
        } else {
          this.cdData.nextCD -= 1
        }
      }, 1000)
    },
    clearNextGameCD () {
      this.cdData.nextCD = 5
      if (this.nextGameCD) {
        clearInterval(this.nextGameCD)
        this.nextGameCD = null
      }
    },
    getBetNum () {
      var curGameData = this.gameListData.find(item => {
        return item.game === this.curGame
      })
      var gameId = curGameData ? curGameData.gameid : null
      if (!gameId) return
      this.eos.getTableRows({
        code: this.$config.cont_owner,
        scope: this.$config.cont_owner,
        table: 'cargame',
        limit: 1,
        index_position: '3',
        lower_bound: gameId + '',
        key_type: 'i64',
        upper_bound: gameId + '',
        json: true
      }).then(res => {
        // console.log(res.rows)
        if (res.rows && res.rows[0]) {
          this.curBetNum = res.rows[0].peoples
        }
      }).catch(e => {
        console.log('cargame table e:', e.message)
      })
    },
    getBetNumInterval () {
      if (this.betNumInterval !== null) {
        clearInterval(this.betNumInterval)
      }
      this.betNumInterval = setInterval(() => {
        this.getBetNum()
      }, 1000)
    },
    getBetGameId () { // 获取下注的gameid
      // console.log(this.gameListData)
      var betType
      if (this.track3.find(item => item.isBet)) {
        betType = 3
      }
      if (this.track5.find(item => item.isBet)) {
        betType = 5
      }
      if (this.track7.find(item => item.isBet)) {
        betType = 7
      }
      if (!betType) {
        return ''
      } else {
        var gameData = this.gameListData.find(item => item.game === betType)
        return gameData.gameid
      }
    },
    toggleShowList (val) {
      if (val) {
        this.showBetRecord = true
      } else {
        this.showBetRecord = false
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
